//
//  NSArray+Extension.m
//  TableDemo
//
//  Created by jutuo on 2020/3/24.
//  Copyright © 2020 jutuo. All rights reserved.
//

#import "NSArray+Extension.h"
#import "NSObject+Extension.h"
@implementation NSArray (Extension)
+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:@selector(objectAtIndex:) with:@selector(xy_objectAtIndex:) class:objc_getClass("__NSArrayI")];
    });
}
- (id)xy_objectAtIndex:(NSUInteger)index
{
    if (self.count == 0) {
        return nil;
    }
    
    if (index > self.count - 1) {
         return nil;
    }
    return [self xy_objectAtIndex:index];
}

- (id)objectOrNilAtIndex:(NSUInteger)index {
    return index < self.count ? self[index] : nil;
}
@end

@implementation NSMutableArray (Extension)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:@selector(objectAtIndex:) with:@selector(xy_mutableObjectAtIndex:) class:objc_getClass("__NSArrayM")];
    });
}

- (id)xy_mutableObjectAtIndex:(NSUInteger)index
{
    if (self.count == 0) {
        return nil;
    }
    
    if (index > self.count - 1) {
         return nil;
    }
    return [self xy_mutableObjectAtIndex:index];
}

- (void)removeFirstObject
{
    if (self.count) {
        [self removeObjectAtIndex:0];
    }
}

- (void)insertObjects:(NSArray *)objects atIndex:(NSUInteger)index
{
    NSUInteger i = index;
    for (id obj in objects) {
        [self insertObject:obj atIndex:i++];
    }
}

- (void)reverse
{
    NSUInteger count = self.count;
    int mid = floor(count / 2.0);
    for (NSUInteger i = 0; i < mid; i++) {
        [self exchangeObjectAtIndex:i withObjectAtIndex:(count - (i + 1))];
    }
}
@end
